package com.ark.frigate.zookeeper.state;

import java.util.EnumSet;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author ZengWeiLong
 * @Description Copy Right Beyonca
 * @Date 2022/3/25 20:12
 * @Version 1.0
 */
@Component
public class OrderStateMachineBuilder {

    final static String MACHINEID = "orderMachine";

    private final static String INSTALL_MACHINE_ID = "InstallOrderMachine";

    /**
     * 构建状态机
     *
     * @param beanFactory
     *
     * @return
     *
     * @throws Exception
     */
    public StateMachine<OrderStates, OrderEvents> build(BeanFactory beanFactory, OrderStates orderState)
            throws Exception {
        StateMachineBuilder.Builder<OrderStates, OrderEvents> builder = StateMachineBuilder.builder();

        System.out.println("构建订单状态机");
        builder.configureConfiguration()
                .withConfiguration()
                .machineId(MACHINEID)
                .beanFactory(beanFactory);

        builder.configureStates()
                .withStates()
                .initial(orderState)
                .states(EnumSet.allOf(OrderStates.class));

        builder.configureTransitions()
                .withExternal()
                .source(OrderStates.UNPAID).target(OrderStates.WAITING_FOR_RECEIVE)
                .event(OrderEvents.PAY)
                .and()
                .withExternal()
                .source(OrderStates.WAITING_FOR_RECEIVE).target(OrderStates.DONE)
                .event(OrderEvents.RECEIVE);
        return builder.build();
    }
}
